<?php


namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\ImageUploadRequest;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Base\Services\ConfigService;
use App\Services\Business\Models\Photo;
use App\Services\Member\Models\User;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use App\Businesses\BusinessState;
use App\Http\Requests\Company\AppraiseRequest;
use App\Services\Business\Models\Appraise;
use App\Services\Business\Services\AppraiseService;
use App\Services\Business\Interfaces\AppraiseServiceInterface;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class AppraiseController extends BaseController
{


    /**
     * @var AppraiseService
     */
    protected $appraiseService;
    /**
     * @var UserService
     */
    protected $userService;

    protected $businessState;


    public function __construct(
        AppraiseServiceInterface $appraiseService,
        UserServiceInterface     $userService,
        BusinessState            $businessState
    )
    {
        $this->appraiseService = $appraiseService;
        $this->userService = $userService;
        $this->businessState = $businessState;

    }

    /**
     * 资源的评价列表
     * @param Request $request
     * @param $type
     * @param $id
     * @return JsonResponse
     */
    public function appraises(Request $request, $type, $id)
    {

        $userKeyWords = $request->input('user_keywords');
        $isRecommend = $request->input('is_recommend');
        $userIds=[];
        if ($userKeyWords) {
            $userIds = User::query()
                ->where('nick_name', 'like', '%' . $userKeyWords . '%')
                ->orWhere('mobile', $userKeyWords)
                ->orWhere('uuid', $userKeyWords)
                ->select(['id'])->get()->pluck('id')->toArray();
        }
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $appraises = $resource->appraises()->with(['photos'])
            ->when($userIds,function ($query) use ($userIds){
                $query->whereIn('user_id',$userIds);
            })
            ->when($isRecommend,function ($query) use ($isRecommend){
                $query->where('is_recommend',$isRecommend);
            })
            ->orderBy('updated_at','desc')->paginate($request->input('size', 20));
        return $this->successData(compact('appraises'));
    }


    /**
     * 评价列表
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request)
    {

        $keywords = $request->input('keywords', '');
        $size = $request->input('size', 10);
        $userKeyWords = $request->input('user_keywords');
        $userIds = [];
        if ($userKeyWords) {
            $userIds = User::query()
                ->where('nick_name', 'like', '%' . $userKeyWords . '%')
                ->orWhere('mobile', $userKeyWords)
                ->orWhere('uuid', $userKeyWords)
                ->select(['id'])->get()->pluck('id')->toArray();
        }
        $appraises = Appraise::query()
            ->with(['user:id,avatar,nick_name,mobile,uuid'])
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('content', 'like', '%' . $keywords . '%');
            })
            ->when($userIds,function ($query) use ($userIds){
                $query->whereIn('user_id',$userIds);
            })
            ->whereNotNull('appraiseable_id')
            ->orderBy('created_at','desc')
            ->paginate($size);
        return $this->successData(compact('appraises'));
    }


    /**
     * 评价导入
     * @param Request $request
     * @return JsonResponse
     */
    public function import(Request $request)
    {

        $companyId= $this->loginCompanyId();
        $data = $request->input('data');
        if (!$data) {
            return $this->error(__('数据为空'));
        }
        $rows = [];
        foreach ($data as  $item) {
            $content = $item[0] ?? '';
            $rows[] = [
                'company_id' =>$companyId,
                'content' => $content,
                'star' => 5,
                'is_used' => -1,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ];
        }
        DB::transaction(function () use ($rows) {
            foreach (array_chunk($rows, 100) as $item) {
                Appraise::insert($item);
            }
        });

        return $this->success(__('导入评价成功'));

    }

    /**
     * 模板列表
     * @param Request $request
     * @return JsonResponse
     */
    public function templates(Request $request)
    {
        $keywords = $request->input('keywords', '');
        $size = $request->input('size', 20);
        $appraises = Appraise::query()
            ->with(['photos', 'user'])
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('content', 'like', '%' . $keywords . '%');
            })
            ->where('user_id', 1)
            ->whereNull('appraiseable_id')
            ->orderBy('updated_at','desc')
            ->paginate($size);
        return $this->successData(compact('appraises'));


    }


    /**
     * 评价的上传图片
     * @param ImageUploadRequest $request
     * @return JsonResponse
     */
    public function photoUpload(ImageUploadRequest $request)
    {
        $file = $request->filldata();
        $prefix ='photo/'.date("Ymd");
        $data=  save_image($file,$prefix);
        return $this->successData($data);
    }

    /**
     * 插入图片
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function  photoStore(Request $request, $id)
    {
        $photos = $request->input('photos');
        if (!is_array($photos)) {
            return $this->error(__('参数错误'));
        }
        $appraise = Appraise::find($id);
        $appraise->photos()->createMany($photos);
        return $this->success(__('图片保存成功'));

    }

    /**
     * 删除oss及数据库的记录
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function photoDelete(Request $request, $id)
    {

        $photo = Photo::find($id);
        Storage::disk(config('zesow.upload.image.disk'))->delete($photo->path);
        $photo->delete();
        return $this->success(__('删除图片成功'));
    }


    public function contentUpdate(Request $request, $id)
    {
        $content = $request->input('content');
        $appraise = Appraise::find($id);
        $appraise->update(['content' => $content]);
        return $this->success(__('内容更新成功'));

    }


//    推荐列表
    public function recommends(Request $request)
    {

        $appraises = Appraise::query()
            ->with(['user:id,avatar,nick_name', 'user.profile'])
            ->where('is_recommend', 1)
            ->take(4)
            ->get()->toArray();
        return $this->successData(compact('appraises'));
    }




    public function obtain()
    {

        $userId = $this->id();

        if (Appraise::query()->where('user_id', $userId)->where('is_used', 1)->exists()) {
            return $this->error(__('您已经领取过评价'));
        }
        $appraiseIds = Appraise::query()->where('is_used', -1)->pluck('id')->toArray();
        $randomIndex = array_rand($appraiseIds);
        $randomId = $appraiseIds[$randomIndex];
        $appraise = Appraise::query()->with(['images'])->where('id', $randomId)->first();
        $appraise->update(['is_used' => 1, 'user_id' => $userId]);
        return $this->successData(compact('appraise'));


    }

    public function entrance()

    {
        $userId = $this->id();
        $appraise = [];
        /**
         * @var ConfigService $configService
         */
        $configService = app()->make(ConfigServiceInterface::class);
        $letter = $configService->getMemberLetter();
        $hasClaimed = Appraise::query()->where('user_id', $userId)->where('is_used', 1)->exists() ?: false;
        if ($hasClaimed) {
            $appraise = Appraise::query()->with(['images'])->where('user_id', $userId)->where('is_used', 1)->first() ?? [];
        }
        return $this->successData(compact('hasClaimed', 'appraise', 'letter'));
    }


    /**
     * 新增一条评价
     * @param AppraiseRequest $request
     * @param Appraise $appraise
     * @return JsonResponse
     */
    public function store(AppraiseRequest $request, Appraise $appraise)
    {


        $data = $request->filldata();
        $appraise ->fill($data)->save($data);
        $data['photos'] && $appraise->photos()->createMany($data['photos']);
        return $this->success(__('新增评价成功'));
    }

    /**
     * 删除评价
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function delete(Request $request, $id)
    {

        $appraise = Appraise::find($id);
        DB::transaction(function () use ($appraise) {
            //删除oss图片
            Storage::disk(config('zesow.upload.image.disk'))->delete($appraise->photos()->get()->pluck('path')->toArray());
            //删除评价
            $appraise->delete();
            //删除图片记录
            $appraise->photos()->delete();

        });

        return $this->success(__('评价删除成功'));
    }

    public function batchDelete(Request $request)
    {
        $ids = $request->input('ids', []);
        $ids = (is_array($ids)) ? $ids : [$ids];
        $appraises = Appraise::query()->with(['photos'])->whereIn('id', $ids)->get();
        DB::transaction(function () use ($appraises,$ids) {
            Appraise::destroy($ids);
            $photoPaths = $photoIds = [];
            foreach ($appraises as $appraise) {
                foreach ($appraise->photos as $photo) {
                    $photoPaths[] = $photo->path;
                    $photoIds[] = $photo->id;
                }
            }
            Photo::destroy($photoIds);
            Storage::disk(config('zesow.upload.image.disk'))->delete($photoPaths);
        });

        return $this->success(__('批量删除成功'));


    }


    /**编辑
     * @param $id
     * @return JsonResponse
     */
    public function edit($id)
    {

        $appraise = Appraise::query()
            ->with(['photos'])
            ->where('id', $id)->firstOrFail();

        return $this->successData(compact('appraise'));
    }


    /**更新
     * @param AppraiseRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(AppraiseRequest $request, $id)
    {

        $appraise = Appraise::query()->where('id', $id)->firstOrFail();
        $data = $request->filldata();
        $appraise->fill($data)->save();
        //删除图片
        $appraise->photos()->delete();
        $appraise->photos()->createMany($data['photos']);
        return $this->success(__('评价更新成功'));
    }

    /**推荐成功
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function recommend(Request $request, $id)
    {
        Appraise::find($id)->update(['is_recommend' => 1]);
        return $this->success(__('评价推荐成功'));

    }

    /**
     * 取消推荐
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function unrecommend(Request $request, $id)
    {
        Appraise::find($id)->update(['is_recommend' => 0]);
        return $this->success(__('取消推荐成功'));

    }

    /**
     *  批量推荐
     * @param Request $request
     * @return JsonResponse
     */
    public function batchRecommend(Request $request)
    {
        $ids = $request->input('ids', []);
        if (!$ids) {
            return $this->error('参数有错');
        }
        Appraise::query()->whereIn('id', $ids)->update(['is_recommend' => 1]);
        return $this->success(__('批量推荐成功'));

    }


}
